#include "stdafx.h"
#include "ZMessageFetcher.h"
#include "ZNetworkReceiveBuffer.h"
#include "ZNetworkReceiver.h"
#include "ZNetworkGenericMessage.h"

namespace	Z	{

//------------------------------------------------------------------------------------------------------------------------
NetworkGenericMessage* MessageFetcher::fetch(NetworkReceiveBuffer& kBuffers, NetworkReceiver& kNetworkReceiver)
{
	size_t kSize	= 0;
	if(kBuffers.getReadableSize() < sizeof(kSize))	{
		return nullptr;
	}
	kBuffers.peek((void*)&kSize, sizeof(kSize));
	if(kSize == 0)	{
		kNetworkReceiver.shutdown();
		return nullptr;
	}
	const size_t necessaryPacketSize	= sizeof(kSize) + kSize;
	const size_t readableBufferSize	= kBuffers.getReadableSize();
	if(readableBufferSize < necessaryPacketSize)	{
		const size_t currentBufferSize	= readableBufferSize + kBuffers.getReceivableSize();
		if(currentBufferSize < necessaryPacketSize)	{
			kBuffers.reserve(necessaryPacketSize - readableBufferSize);
		}
		return nullptr;
	}

	kBuffers.pop(sizeof(kSize));
	NetworkGenericMessage* pMessage	= new NetworkGenericMessage(kNetworkReceiver.getNetworkId(), kSize);
	kBuffers.peek(pMessage->getBuffer(), kSize);
	pMessage->onWritten(kSize);
	kBuffers.pop(kSize);
	return pMessage;
}

}